//存放登录、注册接口
const express = require('express');

const db = require('../db')
const md5 = require('md5');
const jwt = require('jsonwebtoken');

//创建router对象（实际是个函数）
const router = express.Router();


//验证的中间件
router.use((req, res, next) => {
  let {username, password} = req.body;
  if(username.length < 3 || username.length > 6) return next('用户名长度不能小于3位，也不能大于6位');
  if(password.length < 6 || password.length > 10) return next('密码不能小于6位，也不能大于10位');
  next();
});

// 注册接口
router.post('/reguser', (req, res) => {
  let {username, password} = req.body;
  //密码进行md5加密
  password = md5(password);
  // 验证用户名是否存在
  db(`select * from user where username='${username}'`, (err, result) => {
    if(err) throw err;
    if(result.length > 0) {
      res.send({status: 1, message: '账号已存在'});
    }else {
      //注册成功，添加注册信息到数据库
      db(`insert into user set username='${username}', password='${password}'`, (err, result) => {
        if(err) throw err;
        res.send({status: 200, message: '注册成功'});
      })
    }
  })
});


//登录接口
router.post('/login', (req, res) => {
  let {username, password} = req.body;
  //密码进行md5加密
  password = md5(password);
  // 验证用户名和密码是否匹配
  db(`select * from user where username='${username}' and password='${password}'`, (err, result) => {
    if(err) throw err;
    if(result.length > 0) {
      //登录成功，创建token
      // let token = jwt.sign(对象格式的数据， 字符串格式的key, 对象格式的配置项 )
      let token = jwt.sign({id: result[0].id}, 'gjhfjkdsjfhdcvfgq3fdsf', {expiresIn: '2h'});
      res.send({status: 0, message: '登录成功', token: `Bearer ${token}`});
    }else {
      res.send({status: 1, message: '账号或密码错误'})
    }
  })
});


//导出路由对象（函数）
module.exports = router;

//错误的中间件
router.use((err, req, res, next) => {
  res.send({status: 1, message: err});
})